'''
Created on Dec 13, 2009

@author: Juan Catalano
@warning: Needs a serious error manipulation.

Might be extended to add more functionalities.

'''
import os
import settings
from BeautifulSoup import BeautifulStoneSoup
from BeautifulSoup import Tag, NavigableString
from uuid import uuid4
from sets import Set
BASE_XML = '<?xml version="1.0" encoding="UTF-8"?><playlist version="1" xmlns="http://xspf.org/ns/0/"></playlist>'
BASE_URL = 'http://catadesk.no-ip.org:8000/media/playlists/'

BASE_DIR = os.path.join(settings.ROOT_PATH, 'media/playlists/')

class Playlist(object):
    ''' Class to manipulate a playlist.
    '''
    file = None
    name = None
    soup = None
    filename = None
    songs = None
    
    def __init__(self, name=None):
        '''
        Constructor
        '''
        self.name = name
        self.filename = str(uuid4()) + '.xspf'
        print BASE_DIR + self.filename
        self.file = open(BASE_DIR + self.filename, 'w')
        self.soup =  BeautifulStoneSoup(BASE_XML)
        
        if self.name is not None:
            title = Tag(self.soup, 'title')
            title.insert(0, self.name)
            self.soup.playlist.insert(0, title)
        
        self.file.write(str(self.soup))
        self.file.close()
        self.songs = Set()
        
        
    def addSongs(self, songs):

        songs = BeautifulStoneSoup(songs)
        new_songs = Set([s['value'] for s in songs('song')])


        diff = new_songs.difference(self.songs)

        for sng in songs('song'):
            if sng['value'] in diff:
                self.__addSong(sng.contents[0], None, sng['value'])

             
    #  def __delSong(self, location):
    #      
    #      self.songs.remove(location)
    #      
    #      for t in self.soup.playlist.tracklist('track'):
    #          if t.location.contents[0] == location:
    #              t.extract()
    #              self.__persist()
    #              return True
    #      return False 
              
    def __addSong(self, name, artist, location):
        
        if location is None:
            #Location IS REQUIRED
            return False
        
        
        if self.soup.playlist.trackList is None:
            new_track_list = Tag(self.soup, 'trackList')
            self.soup.playlist.insert(0, new_track_list)
        
        new_track = Tag(self.soup, 'track')
        
        if name is not None:
            title = Tag(self.soup, 'title')
            title.insert(0, NavigableString(name.strip()))
            new_track.insert(0, title)
        
        if artist is not None:
            creator = Tag(self.soup, 'creator')
            creator.insert(0, NavigableString(artist))
            new_track.insert(0, creator)
        
        mp3url = Tag(self.soup, 'location')
        
        mp3url.insert(0, NavigableString(location))
        
        new_track.insert(0, mp3url)
        
        self.soup.playlist.trackList.insert(0, new_track)
        
        self.__persist()
        
        self.songs.add(location)
        
        return True
    
    def __persist(self):
        self.file = open(BASE_DIR + self.filename, 'w')
        
        self.file.write(str(self.soup))
        
        self.file.close()
        
    def get_url(self):
        
        return BASE_URL + self.filename
    
    def delete(self):
        self.file.close()
        os.remove(BASE_DIR + self.filename)

